﻿using System;
using System.IO;
using System.Text;

namespace Epic.Core
{
    // borrowed the idea from http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers
    public sealed class ActionLineWriter : TextWriter
    {
#pragma warning disable 1591

        private readonly Action<string> mAction;
        private readonly StringBuilder mBuffer = new StringBuilder();
        private bool mCarriageReturnHappened = false;

        public ActionLineWriter(Action<string> action)
        {
            this.mAction = action;
        }

        private void FlushLine()
        {
            mAction(mBuffer.ToString());
            mBuffer.Clear();
        }

        public override void Write(char value)
        {
            mBuffer.Append(value);

            switch (value)
            {
                case '\n':
                    if (mCarriageReturnHappened)
                        mCarriageReturnHappened = false;
                    else
                        FlushLine();
                    break;
                case '\r':
                    mCarriageReturnHappened = true;
                    FlushLine();
                    break;
            }
        }

        public override Encoding Encoding
        {
            get { return Encoding.Default; }
        }
    }
}
